<!--
 * @description  : 案件-送达方式确认书
 * @descriptionDetail: 案件-送达方式确认书
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-08-25 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="false" backText="" title="送达方式确认书">
      <view class="white-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit?'预览':'打印' }}
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="main-content">
      <view style="width: calc(100% + 30px);">
        <form-section title="送达方式确认书"></form-section>
      </view>
      <u-form
        label-width="auto"
        label-position="top"
        class="form-content"
        :model="docIns"
        :error-type="['border-bottom','message',]"
        ref="uForm"
      >
        <u-form-item label="立案编号" :label-position="labelPosition" :required="true" prop="caseCode">
          <u-input
            type="text"
            :clearable="false"
            :disabled="true"
            placeholder=""
            v-model="docIns.caseCode"
          />
        </u-form-item>
        <u-form-item label="案由" :label-position="labelPosition" :required="true" prop="caseOfAction" ref="caseChangeRef" right-icon="arrow-right">
          <u-input type="textarea" height="35" :auto-height="true" placeholder="请选择" :disabled="true" :custom-style="pointerStyle" v-model="docIns.caseOfAction" @click="()=>{if(state.canEdit) choiceCaseOfAction()}" />
        </u-form-item>
        <u-form-item label="告知事项" :label-position="labelPosition" :required="true">
          <u-input type="textarea" height="35" :auto-height="true" placeholder="请选择" :disabled="true" :custom-style="pointerStyle" v-model="noticeText" />
        </u-form-item>
        <u-form-item label="当事人" :required="true" right-icon="arrow-right">
          <u-input placeholder="请输入" :disabled="true" :custom-style="pointerStyle"  v-model="docIns.party" @click="()=>{if(state.canEdit) partySelectShow = true}" />
        </u-form-item>
        <view style="margin:0px -15px 0px -15px;">
          <u-gap :height="$theme.cm_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
        </view>
        <view style="width: calc(100% + 30px);">
          <form-section title="送达方式及地址"></form-section>
        </view>
        <u-form-item label="指定签收人" prop="designatedReceiver">
          <u-input
            placeholder="请输入"
            :disabled="!state.canEdit"
            v-model="docIns.designatedReceiver"
          />
        </u-form-item>
        <u-form-item prop="isXyfConfirm" :required="true" label="送达方式">
          <u-checkbox-group @change="radioGroupChange" :disabled="!state.canEdit">
            <u-checkbox
              v-for="(item, index) in modeList"
              :key="index"
              v-model="item.checked"
              :name="item.value"
            >
              <view class="flex-text-row check-list-item">
                <text class="u-m-r-10" style="width: 120rpx;">
                  {{ item.name }}
                </text>
                <u-input
                  v-if="item.value === '99'"
                  :disabled="!state.canEdit"
                  placeholder="请输入"
                  type="text"
                  v-model="docIns.otherRemark"
                ></u-input>
              </view>
            </u-checkbox>
          </u-checkbox-group>
        </u-form-item>
        <u-form-item prop="serviceAddress" label="确认送达地址">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入确认送达地址"
            type="text"
            v-model="docIns.serviceAddress"
          />
        </u-form-item>
        <u-form-item label="电子送达类型" label-position="top">
          <u-checkbox-group @change="checkboxGroupChange" :disabled="!state.canEdit">
            <u-checkbox
              v-for="(item, index) in decisionWayList"
              :key="index"
              v-model="item.checked"
              :name="item.value"
            >
              <view class="flex-text-row check-list-item">
                <text class="u-m-r-30" style="width: 200rpx;">
                  {{ item.name }}
                </text>
                <u-input
                  type="text"
                  :disabled="!state.canEdit || item.disabled"
                  :border="true"
                  v-model="docIns[item.filedName]"
                ></u-input>
              </view>
            </u-checkbox>
          </u-checkbox-group>
        </u-form-item>
        <u-form-item
          label="受送达人签名"
          prop="isReadBoolean"
          :label-position="labelPosition"
          :required="true"
        >
          <u-checkbox-group width="100%" :disabled="!state.canEdit">
            <u-checkbox
              v-model="isReadBoolean"
              @change="checkboxChange"
            >
              我已阅读（听明白）本确认书的告知事项，提供了上栏送达地址，确认了上栏送达方式，并保证所提供的送达地址各项内容是正确的、有效的。如在行政处罚过程中送达地址发生变化，将及时通知贵局。未及时告知贵局的，按上述地址送达即发生法律效力。
            </u-checkbox>
          </u-checkbox-group>
        </u-form-item>
        <u-form-item label-position="top" :required="true" label="执法人员签名" prop="undertakerUuids">
          <u-input
            :disabled="true"
            placeholder=""
            type="text"
			:custom-style="pointerStyle"
            v-model="docIns.undertaker"
          />
        </u-form-item>
        <u-form-item label="执法日期" :required="true" right-icon="arrow-right" prop="enforcerTime" ref="dateChangeRef">
          <u-input :disabled="true" :custom-style="pointerStyle" placeholder="请选择日期" v-model="docIns.enforcerTime" @click="()=>{if(state.canEdit)isShowRegDate = true}" />
        </u-form-item>
        <u-form-item label="备注" :label-position="labelPosition">
          <u-input type="textarea" height="100" :disabled="!state.canEdit" :auto-height="true" placeholder="请输入" v-model="docIns.remark" />
        </u-form-item>
      </u-form>
    </view>
    <!-- 底部按钮开始 -->
    <view class="submit-btns btn-other-cls" v-if="state.canEdit">
      <u-button plain class="u-btn" type="primary" @click="saveOrSubmit('save')">
        保存
      </u-button>
      <u-button class="u-btn" type="primary" @click="saveOrSubmit('submit')">
        提交
      </u-button>
    </view>
    <!-- 底部按钮结束 -->
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
    <u-popup mode="bottom" height="80%" v-model="partySelectShow">
      <select-party-component :params="partyParams" :isCheckBox="false" @choose="handlerChooseParty"></select-party-component>
    </u-popup>
    <u-calendar mode="date" v-model="isShowRegDate" @change="changeDate('enforcerTime',$event)"></u-calendar>
    <u-calendar mode="date" v-model="isShowGiveDate" @change="changeDate('giveTime',$event)"></u-calendar>
  </view>
</template>
<script>
import caseCommon from "../caseCommonMixin.js";
import officeService from "@/service/case/office.service.js";
import FormSection from "@/components/form-section.vue";
import PersonSelection from "@/pages/case/components/personSelection.vue";
import zjCommonService from "@/service/common/common.service";
import SelectPartyComponent from "../components/selectPartyComponent.vue";
import caseService from '@/service/case/case.service.js';
import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			FormSection,
			fabButton,
			PersonSelection,
			SelectPartyComponent,
		},
		mixins: [caseCommon, ],
		data() {
			return {
				labelPosition: 'top',
				personSelectShow: false,
				psParam: {},
				rules: {
					caseCode: [{
						required: true,
						message: '请填写立案编号',
						trigger: ['change', 'blur', ],
					}, ],
					caseOfAction: [{
						required: true,
						message: '请选择案由',
						trigger: ['change', 'blur', ],
					}, ],
				},
				doc: {},
				docIns: {}, // 表单数据
				btnType: "",
				noticeText: "1、为便于当事人及时收到相关法律文书，保证行政处罚程序顺利进行，当事人应当如实提供确切的送达地址。\n 2、如果提供的地址不确切，或不及时告知变更后的地址，使法律文书无法送达或未及时送达，当事人将自行承担由此可能产生的法律后果。\n 3、为提高送达效率，本局可以采用传真、电子邮件、短信、微信、钉钉等方式送达法律文书。以发送方设备显示发送成功。 \n 4、确认的送达地址适用于行政处罚程序、听证程序、执行程序。如果送达地址有变更，应当及时书面告知本局变更后的送达地址。",
				partySelectShow: false,
				partyList: [], // 当事人列表
				partyParams: {}, // 传给当事人选择页面的参数
				modeList: [{
						name: '直接送达',
						checked: false,
						value: '02',
						disabled: true,
					},
					{
						name: '邮寄送达',
						checked: false,
						value: '01',
						disabled: true,
					},
					{
						name: '电子送达',
						checked: false,
						value: '04',
						disabled: true,
					},
					{
						name: '其他',
						checked: false,
						value: '99',
						disabled: true,
					},
				], // 送达方式
				decisionWayList: [{
						name: '手机号码',
						checked: false,
						value: '01',
						filedName: 'phone',
						disabled: true,
					},
					{
						name: '微信号',
						checked: false,
						value: '02',
						filedName: 'wechatNumber',
						disabled: true,
					},
					{
						name: '钉钉号',
						checked: false,
						value: '03',
						filedName: 'nailNumber',
						disabled: true,
					},
					{
						name: '电子邮件地址',
						checked: false,
						value: '04',
						filedName: 'mailAddress',
						disabled: true,
					},
					{
						name: '传真号码',
						checked: false,
						value: '05',
						filedName: 'faxPhone',
				          disabled: true,
				        },
				        {
				          name: "其他",
				          checked: false,
				          value: "06",
				          filedName: "other",
						disabled: true,
					},
				], // 电子送达地址
				isShowOtherRemark: false,
				isReadBoolean: false,
				decisionWayArray: [],
				isShowRegDate: false,
				isShowGiveDate: false,
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}],
				// h5端部分浏览器input设置disabled后点击事件失效 2023-10-27 fsx start
				pointerStyle: {
				  marginRight: "5px",
					pointerEvents: "none !important"
				},
				// h5端部分浏览器input设置disabled后点击事件失效 2023-10-27 fsx end
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad() {
			this.caseParam = this.getRouteParam();
		},
		watch: {
			isShowRegDate(newValue, oldValue) {
				this.$refs.dateChangeRef.validation();
			},
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo;
				this.setRightBtns();
			});
			this.initDocData();
		},
		methods: {
			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			// 送达方式触发事件
			radioGroupChange(e) {
				this.docIns.isXyfConfirm = e.sort().join(',');
				console.log(this.docIns.isXyfConfirm)
			},
			// 电子送达地址触发事件
			checkboxGroupChange(e) {
				debugger
				this.decisionWayArray = e;
				let decisionWayStr = this.decisionWayArray.join(',');
				this.decisionWayList.forEach((item) => {
					if (decisionWayStr.indexOf(item.value) != -1) {
						item.disabled = false;
					} else {
						item.disabled = true;
					}
				})
			},
			// 勾选已阅读checkbox事件
			checkboxChange(e) {
				console.log(e);
				this.isReadBoolean = e;
				if (this.isReadBoolean) {
					this.docIns.isRead = 1;
				}
			},
			changeDate(key, e) {
				this.$set(this.docIns, key, this.$u.timeFormat(new Date(e.result).getTime(), 'yyyy年mm月dd日'));
			},
			underTaker() {
				this.psParam = {
					min: 1,
					selectedPsrLst: [],
					caseUuid: this.caseParam.caseUuid,
				};
				this.personSelectShow = true;
			},
			handlerChoosePerson(e) {
				this.personSelectShow = false;
				let employeeList = [...e, ];
				let tIds = [];
				let tNames = [];
				employeeList.forEach(el => {
					tIds.push(el.personUuid);
					tNames.push(el.personName);
				});
				this.docIns.undertakerUuids = tIds.join(",");
				this.docIns.undertaker = tNames.join(",");
			},
			// 初始化文书信息
			initDocData() {
				this.$u.loading('加载中...');
				officeService.docFields(this.caseParam.docUuid, true).then(docConfigs => {
					if (docConfigs.success) {
						// 获取勘验笔录信息参数
						let parms = {
							id: this.caseParam.id,
							docUuid: this.caseParam.docUuid,
							bizUuid: this.caseParam.bizUuid,
						}
						officeService.getDocServiceConfirm(parms).then(res => {
							this.$u.hideLoading();
							let [tiInfo, rs, ] = [{}, {}, ];
							if (res.success && res.data.length === 2) {
								tiInfo = res.data[0];
								rs = res.data[1];
								Object.keys(tiInfo).forEach(key => {
									rs[key] = tiInfo[key];
								});
							} else {
								rs = res.data[0];
							}
							this.objMerge(this.docIns, rs);
							this.isReadBoolean = this.docIns.isRead == 1 ? true : false;
							if (this.docIns.decisionWay) {
								this.decisionWayArray = this.docIns.decisionWay.indexOf(',') != -1 ? this.docIns.decisionWay.split(",") : [this.docIns.decisionWay, ];
								console.log(this.decisionWayArray);
								this.decisionWayList.forEach((item) => {
									if (this.docIns.decisionWay.indexOf(item.value) != -1) {
										item.checked = true;
										item.disabled = false;
									}
								})
							}
							// 修改标准版本 bug（送达类型为空是送达方式回显问题）2024-8-8 fsx 开始
							if(this.docIns.isXyfConfirm) {
								this.modeList.forEach((item) => {
									if (this.docIns.isXyfConfirm.indexOf(item.value) != -1) {
										item.checked = true;
										item.disabled = false;
									}
								})
							}
							// 修改标准版本 bug（送达类型为空是送达方式回显问题）2024-8-8 fsx 结束
							this.getPartyInfoList();
						}).catch(er => {
							console.log(er);
							this.$u.hideLoading();
							this.$u.toast(er);
						});
					} else {
						this.$u.toast(docConfigs.msg);
					}
				}).catch(er => {
					console.log(er);
					this.$u.hideLoading();
					this.$u.toast(er);
				});
			},
			choiceCaseOfAction() {
				this.$u.route({
					url: "/pages/case/components/casePropertySelection",
					params: {
						handleProc: "1", // 获取案件类型
					},
				});
			},
			updateBackState(param) {
				if (param.caseSelectionData) { // 案由选择回调
					let arr = [];
					let arrIds = [];
					param.caseSelectionData.map(itm => {
						arr.push(itm.caseProperty);
						arrIds.push(itm.casepropUuid);
					});
					this.docIns.caseOfAction = arr.join('、');
				}
			},
			// 获取当事人list（单选）
			getPartyInfoList() {
				caseService.getPartyInfoList(this.caseParam.bizUuid).then(res => {
					if (!res.success) return;
					this.partyList = res.data.length > 0 ? res.data : [];
					this.partyList.forEach(itm => {
						if (this.docIns.partyUuids === itm.partyUuid) {
							itm.check = true;
							this.docIns.party = itm.partyName;
						}
					});
					this.partyParams = {
						list: this.partyList,
						selUsersStr: this.docIns.partyUuids,
					}
				}).catch((err) => {
					this.partyList = [];
					console.log(err);
				})
			},
			// 选择当事人回调事件
			handlerChooseParty(e) {
				this.partySelectShow = false;
				this.docIns.party = e.partyNames;
				this.partyParams.selUsersStr = e.partyUuids;
				this.docIns.partyUuids = e.partyUuids;
			},
			// 打印/预览
			printOrDown(flag) {
				if (flag) {
					// 调接口预览
					this.saveOrSubmit('preview');
				} else {
					this.downloadFile(this.doc.pdfFileId);
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast("没有文书");
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			// 表单验证
			validForm(type) {
				let basicValid = false;
				this.btnType = type;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						if (!this.docIns.party) {
							this.$u.toast('请选择当事人!');
							return;
						}
						// console.log(this.docIns.isXyfConfirm);
						// console.log(this.docIns.otherRemark);
						if (!this.docIns.isXyfConfirm) {
							this.$u.toast('请选择送达方式!');
							return;
						} else {
							if (this.docIns.isXyfConfirm == '4' && !this.docIns.otherRemark) {
								this.$u.toast('请填写其他送达方式!');
								return;
							}
						}
						if (!this.isReadBoolean) {
							this.$u.toast('请选择受送达人签名');
							return;
						}
						basicValid = true;
					} else {
						basicValid = false;
					}
				});
				return basicValid;
			},
			// 保存或提交
			saveOrSubmit(type) {
				let flag = this.validForm(type);
				if (flag) {
					this.handleOperBtn(type);
				}
			},
			handleOperBtn(flag) {
				let [docGoodsReg, self, ] = [this.docIns, this, ];
				let {
					docUuid,
					id,
					titemUuid,
					type,
					bizUuid,
					caseCode,
					caseType,
					gfaCode,
				} = this.caseParam;
				docGoodsReg.caseUuid = this.caseParam.caseUuid;
				console.log(this.decisionWayArray)
				docGoodsReg.decisionWay = this.decisionWayArray.join(',');
				this.$u.loading('数据保存中...');
				officeService.saveDocServiceConfirm(docGoodsReg, docUuid, titemUuid, id, type).then((res) => {
					this.$u.hideLoading();
					if (res.success) {
						this.$u.toast(res.msg);
						let bean = res.bean;
						let saveData = res.data[0];
						this.docIns = {
							...this.docIns,
							...bean,
						};
						try {
							if (!this.doc) this.doc = res.data[0];
						} catch (e) {
							console.log(e);
						}
						// this.objMerge(this.docIns, docGoodsReg);
						if (flag === 'submit') {
							this.$u.loading('数据提交中...');
							officeService.submitDocServiceConfirm(this.docIns, docUuid, titemUuid, id, type)
								.then(res => {
									this.$u.hideLoading();
									this.saveBehaviorLog(1, this.caseParam, this.doc);
									if (res.success) {
										// 返回列表
										this.$u.toast(res.msg);
										self.backPrev({
											paramKey: "offiList",
											param: {
												caseUuid: bizUuid,
												caseCode: caseCode,
												caseType: caseType,
											},
										});
									} else {
										this.$u.toast(res.msg);
									}
								})
						} else if (flag === 'preview') { // 预览saveData.docInsUuid
							officeService.buildLocalPunish("/cas/case-service-confirm", saveData.docInsUuid)
								.then(
									pdfId => {
										if (pdfId.success) {
											this.downloadFile(pdfId.bean, "预览", false);
										} else {
											this.$u.toast(pdfId.msg);
										}
									});
						} else {
							this.saveBehaviorLog(0, this.caseParam, this.doc);
						}
					} else {
						this.$u.toast(res.msg);
					}
				});
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "../case_common.scss";

	.page {
		padding: 0;
	}

	.doc-no {
		display: inline-block;
		height: 35px;
		width: 60px;
		text-align: center !important;
		flex: none;
	}

	.check-desc {
		display: flex;
		align-items: center;

		.dec-input {
			width: 25%;
		}
	}

	.check-list-item {
		align-items: center;
		width: 100%;
		margin: 5rpx 0rpx;
	}

	/deep/.u-checkbox__label {
		width: 100% !important;
	}
</style>
